package com.example.demo.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * JWT工具类
 *
 * @author Eric Wu
 * @since 1.8
 * create 2020-06-05
 */
@Setter
@Component
@ConfigurationProperties(prefix = "jwt")
public class JWTUtil {

    /**
     * 过期时间
     */
    private Integer expireTimeSecond;
    /**
     * 加密的secret
     */
    private String salt;


    public  boolean verify(String token, String userName,String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC512(salt+secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", userName).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public  String getUserName(String token){
        try{
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        }catch (Exception e){
            return "";
        }
    }

    public String sign(String userName,String secret){
        LocalDateTime nowToExpireTime = LocalDateTime.now().plusSeconds(expireTimeSecond);
        Algorithm algorithm = Algorithm.HMAC512(salt+secret);
        ZonedDateTime nowToExpireTimeWithZoneId = nowToExpireTime.atZone(
                ZoneId.systemDefault());

        return JWT.create().withClaim("username",userName).withExpiresAt(
                Date.from(nowToExpireTimeWithZoneId.toInstant())).sign(algorithm);
    }

}
